package org.example;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.ObjectMapper;

public class test16 {
    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();

        // 注册子类型
        objectMapper.registerSubtypes(Cat.class, Dog.class);

        // 序列化
        Animal cat = new Cat("Tom");
        String catJson = objectMapper.writeValueAsString(cat);
        System.out.println(catJson);

        Animal dog = new Dog("jack");
        String dogJson = objectMapper.writeValueAsString(dog);
        System.out.println(dogJson);

        // 反序列化
        Animal deserializedCat = objectMapper.readValue(catJson, Animal.class);
        System.out.println("Name: " + deserializedCat.getName());

        Animal deserializedDog = objectMapper.readValue(dogJson, Animal.class);
        System.out.println("Name: " + deserializedDog.getName());
    }
}

//告诉Jackson应该使用JSON中的type属性来确定实际的子类类型
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonTypeName("Animal")
abstract class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

@JsonTypeName("Cat")
class Cat extends Animal {
    public Cat() {
        // 默认构造函数
        super("");
    }

    public Cat(String name) {
        super(name);
    }
}

@JsonTypeName("Dog")
class Dog extends Animal {
    public Dog() {
        // 默认构造函数
        super("");
    }

    public Dog(String name) {
        super(name);
    }
}
